﻿#region References

using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data.Objects;
using System.Data.Objects.DataClasses;
using Data.Model;

#endregion

namespace Data.Repositories
{
    internal abstract class Repository<T> : IRepository<T> where T : EntityObject
    {
        #region Fields

        private ObjectSet<T> _objectSet; 

        #endregion

        #region Constructor

        protected Repository()
        {
            DomainContext = new EntitiesModelContainer();
        }

        #endregion

        #region Properties
        
        internal EntitiesModelContainer DomainContext { get; private set; }
        public IEnumerable<T> CachedObjects { get; private set;}

        #endregion

        #region Methods
        
        public virtual void RefreshCache()
        {
            Load();
            if (CachedObjects != null)
            {
                DomainContext.Refresh(RefreshMode.StoreWins, CachedObjects);
            }
        }

        public virtual void Load()
        {
            _objectSet = DomainContext.CreateObjectSet<T>();
            CachedObjects = new ObservableCollection<T>(_objectSet);
        }

        public virtual void SaveChanges()
        {
            DomainContext.SaveChanges();
        }

        public virtual void AddObject(T obj)
        {
            _objectSet.AddObject(obj);
        }

        #endregion
    }
}